using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using ARF.Web.Fields;
using System.Web.UI.WebControls;
using System.Diagnostics;

namespace ARF.Web.Controls
{
    public class CannedQueryField : CannedSiteQuery
    {
        protected DropDownList _queryTitles;

        protected override void OnLoad(EventArgs e)
        {
            if (string.IsNullOrEmpty(ID)) throw new Exception("CannedQueryField ID not set");

            base.OnLoad(e);
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {
                SPList oList = QueriesList;

                if (oList == null)
                {
                    Trace.WriteLine("Inavlid list: " + QueriesListName);
                    return;
                }

                PlaceHolder ph = new PlaceHolder();
                Controls.Add(ph); ph.ID = "Controls";

                if (FormMode == Microsoft.SharePoint.WebControls.SPControlMode.Edit)
                {
                    _queryTitles = new DropDownList(); _queryTitles.ID = "Titles"; _queryTitles.EnableViewState = false;
                    _queryTitles.AutoPostBack = true; _queryTitles.SelectedIndexChanged += new EventHandler(_queryTitles_SelectedIndexChanged);
                    ph.Controls.Add(_queryTitles);

                    foreach (SPListItem oItem in oList.Items)
                    {
                        ListItem oNew = new ListItem(oItem.Title);
                        oNew.Selected = (Title == oItem.Title);
                        _queryTitles.Items.Add(oNew);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }
        }

        void _queryTitles_SelectedIndexChanged(object sender, EventArgs e)
        {
            Title = _queryTitles.SelectedValue;
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (FormMode == Microsoft.SharePoint.WebControls.SPControlMode.Edit)
            {

                base.Render(writer);
            }
            else
                base.Render(writer);
        }

        public override string QueryTitle
        {
            get
            {
                return Title;
            }
            set
            {
                base.QueryTitle = value;
            }
        }

        public string Title
        {
            get
            {
                return ARFProperties.Current.GetStringProperty("CannedQueryField: " + ID);
            }

            set
            {
                ARFProperties.Current.SetProperty("CannedQueryField: " + ID, value);
            }
        }
    }
}
